package com.hefan.club.dynamic.service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.common.meta.UserTypeEnum;
import com.cat.tiger.service.JedisService;
import com.cat.tiger.util.DynamicDateCal;
import com.cat.tiger.util.HttpClientUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hefan.club.comment.bean.MessageResVo;
import com.hefan.club.comment.meta.RedisKeyConstant;
import com.hefan.club.configCenter.ClubConfigCenter;
import com.hefan.club.dynamic.bean.DynamicAlbum;
import com.hefan.club.dynamic.bean.Message;
import com.hefan.club.dynamic.bean.MessageConstant;
import com.hefan.club.dynamic.bean.PraiseLog;
import com.hefan.club.dynamic.dao.DynamicAlbumDao;
import com.hefan.club.dynamic.dao.DynamicDao;
import com.hefan.club.dynamic.itf.DynamicService;
import com.hefan.club.dynamic.itf.cache.RedisDynamicService;
import com.hefan.club.util.StringUtil;
import com.hefan.club.util.VideoTranscodeUtil;
import com.hefan.common.exception.DataIllegalException;
import com.hefan.live.bean.LiveDynamicVo;
import com.hefan.user.bean.RecommendForStar;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.profiler.Profiler;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Component("dynamicService")
public class DynamicServiceImpl implements DynamicService {

  private Logger logger = LoggerFactory.getLogger(DynamicServiceImpl.class);

  @Resource
  private ClubConfigCenter clubConfigCenter;

  @Resource
  private DynamicDao dynamicDao;
  @Resource
  private DynamicAlbumDao dynamicAlbumDao;

  @Resource
  private WebUserService webUserService;

  @Resource
  private WatchService watchService;

  @Resource
  WatchCacheService watchCacheService;

  @Resource
  private VideoTranscodeUtil videoTranscodeUtil;

  @Resource
  private UserAuthService userAuthService;

  @Resource
  private RedisDynamicService redisDynamicService;

  @Resource
  SquareUserCheckService squareUserCheckService;

  @Resource
  private JedisService jedisService;

  @Override
  public Page<Message> listClubIndex(Page po, String userId) {
    List<Message> messageLists = Lists.newArrayList();
    logger.info("用户userId={}，pageNo={},pageSize={}查看关注人信息", userId, po.getPageNo(), po.getPageSize());
    try {
      //0.获取关注人列表，关注人ids
      List<String> user = watchCacheService.getAllWatchUserIdList(userId);
      logger.info("用户userid={}获取关注人list size={}", userId, user.size());
      ExecutorService executor = Executors.newCachedThreadPool();
      CountDownLatch barrier = new CountDownLatch(user.size());
      String followListKey = String.format(com.hefan.club.comment.meta.RedisKeyConstant.FOLLOW_FEEDS, userId);
      jedisService.del(followListKey);
      if (!CollectionUtils.isEmpty(user)) {
        for (String id : user) {
          //1.获取单个用户，查询每个人最新20条动态，对动态排序
          if (org.apache.commons.lang3.StringUtils.isNotBlank(id)) {
            executor.submit(new Thread(new Runner(barrier, id, po, userId)));
          }
        }
        //10秒等待
        barrier.await(10, TimeUnit.SECONDS);
        //2.所有任务执行完成，获取最新列表
        if (barrier.getCount() == 0) {
          //最新关注人动态的最新列表
          List<Object> list = jedisService.zrevrange(followListKey, 0, po.getPageSize()-1);
          for (Object id : list) {
            if (id != null) {
              Message message=getCacheMessageInfo(String.valueOf(id), userId);
              if(message!=null){
                //列表页评论数=礼物数+评论数
                message.setCommentCount(message.getPresentCount() + message.getCommentCount());
                messageLists.add(message);
              }
            }
          }
        }
      }
      /**2017-03-28由于动态内容采取，拉流模式，totalPage和totalItems 数值不准确，
       * 兼容处理IOS老版本 当页面显示的条数小于pageSize时，强制显示最后一页
       * */
      if (messageLists.size() < po.getPageSize()) {
        po.setTotalItems(po.getPageSize()*po.getPageNo());
      }else{
        po.setTotalItems(po.getPageSize()*(po.getPageNo()+1));
      }
      po.setResult(messageLists);
    } catch (Exception ex) {
      ex.printStackTrace();
      logger.error("用户userId={}，pageNo={},pageSize={}查看关注人信息异常", userId, po.getPageNo(), po.getPageSize(), ex);
    }
    return po;
  }

  /**
   * 封装message对象，相册内容和动态人基本信息
   *
   * @param messageId
   * @param userId
   * @return
   */
  @Override
  public Message getCacheMessageInfo(String messageId, String userId) {
    Message message = redisDynamicService.getMessageInfo(String.valueOf(messageId));
    if (message == null) {
      return null;
    }
    List<Map<String, String>> mapOther = Lists.newArrayList();
    message.setMessageTimes(DynamicDateCal.getDaysBeforeNow(message.getMessageTime()));
    message.setPraiseType(checkPraise(userId, message.getMessageId().toString()));

    logger.info("拼接动态msgId={}详细，动态类型={}", message.getMessageId(), message.getMessageType());
    if (message.getMessageType().equals(String.valueOf(MessageConstant.VIDEOS)) || message.getMessageType().equals(String.valueOf(MessageConstant.WORDS))) {
      //普通视频
      Map<String, String> map = Maps.newHashMap();
      map.put("month", "");
      map.put("year", "");
      map.put("pictureUrls", message.getPath() == null ? "" : message.getPath());
      mapOther.add(map);
    } else if (message.getMessageType().equals(String.valueOf(MessageConstant.PICTURE))) {
      // 相册
      List<Object> path = redisDynamicService.getDynamicAlbumCache(message.getMessageId());
      for (Object dynamicAlbum : path) {
        logger.info("动态messageId={},相册={}", message.getMessageId(), JSONObject.toJSONString(dynamicAlbum));
        Map<String, String> map = Maps.newHashMap();
        map.put("month", "");
        map.put("year", "");
        map.put("pictureUrls", dynamicAlbum== null ? "" : String.valueOf(dynamicAlbum));
        mapOther.add(map);
      }
    }
    message.setArticleContent(mapOther);
    // 获取对象信息
//    WebUser user = webUserService.getWebUserInfoByIsDel(message.getUserId(),2);
    WebUser user = webUserService.findUserInfoFromCache(message.getUserId());
    if (user == null) {
      logger.info("用户信息不存在userId={},messageId={}", message.getUserId(), message.getMessageId());
      return null;
    }
    //赞数=额外赞数+真实赞数
    message.setPraiseCount((message.getEwaizan() == null ? 0 : message.getEwaizan()) + message.getPraiseCount());
    message.setUserLevel(user.getUserLevel());
    message.setUserType(String.valueOf(user.getUserType() == null ? 0 : user.getUserType()));
    message.setHeadImg(user.getHeadImg());
    message.setNickName(user.getNickName());
    return message;
  }

  /**
   * 线程获取用户动态列表
   */
  class Runner implements Runnable {
    // 一个同步辅助类，它允许一组线程互相等待，直到到达某个公共屏障点 (common barrier point)
    private CountDownLatch barrier;

    private String userId;

    private String anchorId;

    private Page page;

    private Runner(CountDownLatch barrier, String anchorId, Page page, String userId) {
      super();
      this.barrier = barrier;
      this.userId = userId;
      this.page = page;
      this.anchorId = anchorId;

    }

    @Override
    public void run() {
      try {
        String key = String.format(com.hefan.club.comment.meta.RedisKeyConstant.FEEDS, anchorId);
        List<Object> ids = redisDynamicService.getFeedsFromCache(anchorId, page, key,userId);
        //缓存用户当前页
        String followListKey = String.format(com.hefan.club.comment.meta.RedisKeyConstant.FOLLOW_FEEDS, userId);
        if (!CollectionUtils.isEmpty(ids)) {
          //获取单个动态id
          for (Object id : ids) {
            jedisService.zadd(followListKey, Double.parseDouble(String.valueOf(id)), String.valueOf(id));
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
        logger.error("线程={}汇总被关注人userId={}动态内容异常", Thread.currentThread(), userId);
      } finally {
        barrier.countDown();
      }
    }
  }

  /**
   * 用户自己查看和别人访问俱乐部
   * @param page
   * @param userId
   * @param authorId
   * @return
   * @throws Exception
   */
  @Override
  public Page<Message> listMessage(Page page, String userId, String authorId) throws Exception {

    logger.info("authorId={}，访问用户userId={},pageNo={},pageSize={}", authorId, userId, page.getPageNo(), page.getPageSize());
    List<Message> result = Lists.newArrayList();
    WebUser user = webUserService.getWebUserInfoByUserId(userId);

    WebUser author = webUserService.getWebUserInfoByUserId(authorId);
    if (user == null || author == null) {
      logger.error("主播authorId={}俱乐部 userId={}账号不存在或删除", authorId, userId);
      return page;
    }
    //先获取转码中的视频
    List<Object> transcodingList;
    String key = String.format(com.hefan.club.comment.meta.RedisKeyConstant.USER_FEEDS, authorId);
    //自己看自己俱乐部
    if (userId.equals(authorId)) {
      transcodingList = redisDynamicService.getTranscodingList(authorId);
      logger.info("authorId={}，访问用户userId={},转码中动态size={}", authorId, userId, transcodingList.size());
      // 已转码成功的，或者不需要转码数据，存在转码数据则从数据库获取排序，否则从置顶缓存分页获取数据
      if(!CollectionUtils.isEmpty(transcodingList)) {
        transcodingList =Lists.newArrayList();
        List<Message>messages = dynamicDao.listMessageIds(page, userId);
        if (!CollectionUtils.isEmpty(messages)) {
          for(Message map:messages){
            transcodingList.add(map.getMessageId());
          }
        }
      }else {
        transcodingList = redisDynamicService.getFeedsFromCache(authorId, page,key, authorId);
      }
    } else {
      transcodingList = redisDynamicService.getFeedsFromCache(authorId, page,key, userId);
      logger.info("authorId={}，访问用户userId={},主播动态size={}", authorId, userId, transcodingList.size());
    }
    if(!CollectionUtils.isEmpty(transcodingList)) {
      for (Object obj : transcodingList) {
        Message message = getCacheMessageInfo(String.valueOf(obj), userId);
        if (message != null) {
          if (org.apache.commons.lang3.StringUtils.isBlank(message.getTopStatus()) || message.getTopStatus().equals("false")) {
            message.setTopStatus("0");
          }
          //列表页评论数=礼物数+评论数
          message.setCommentCount(message.getPresentCount() + message.getCommentCount());
          result.add(message);
        }
      }
    }

    /**2017-03-28由于动态内容采取，拉流模式，totalPage和totalItems 数值不准确，
     * 兼容处理IOS老版本 当页面显示的条数小于pageSize时，强制显示最后一页，其他情况总页数显示当前页+1
     * */
    if (result.size() < page.getPageSize()) {
      page.setTotalItems(page.getPageSize()*page.getPageNo());
    }else{
      page.setTotalItems(page.getPageSize()*(page.getPageNo()+1));
    }
    page.setResult(result);
    return page;
  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public ResultBean top(String userId, String messageId) {
    ResultBean resultBean = new ResultBean();
    try {
      logger.info("用户userId={},将动态id={}置顶", userId, messageId);
      if (StringUtils.isEmpty(userId)) {
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        return resultBean;
      }
      List<Map<String, Object>> mes = dynamicDao.findTop(userId);
      logger.info("用户userId={},将动态id={}置顶,原是否有置顶size={}", userId, messageId, mes.size());
      // 判断是否有已置顶内容，有则取消置顶
      if (mes.size() > 0) {
        dynamicDao.unTop(userId, mes.get(0).get("id").toString());
        int msgId = Integer.parseInt(mes.get(0).get("id").toString());
        redisDynamicService.updateUserFeedsScore(userId, msgId, (double) msgId * -1);
      }
      int id = dynamicDao.top(userId, messageId);
      if (id > 0) {
        resultBean.setCode(ResultCode.SUCCESS.get_code());
        redisDynamicService.updateUserFeedsScore(userId, Integer.parseInt(messageId), Double.parseDouble(messageId));
      } else {
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
      }
    } catch (Exception e) {
      e.printStackTrace();
      resultBean.setCode(ResultCode.UNSUCCESS.get_code());
    }

    return resultBean;
  }

  @Override
  public Page<Map<String, Object>> photoList(Page po, String isSync, String messageId, String userId) {
    WebUser user = webUserService.findUserInfoFromCache(userId);
    if (user.getState() != 0 || user.getIsDel() == 1 || user.getSuperiorState() != 0) {
      return null;
    }
    return dynamicAlbumDao.photoList(po, userId, isSync, messageId);
  }

  @Override
  public Page<Message> videoList(Page<Map<String, Object>> po, String isSync, String authorId, String userId) throws ParseException {
    Page<Message> result = dynamicDao.videoList(po, isSync, authorId, userId);
    for (Message mes : result.getResult()) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date = sdf.parse(String.valueOf(mes.getMessageTime()));
      mes.setMessageTimes(DynamicDateCal.getDaysBeforeNow(date));
      mes.setPraiseType(checkPraise(userId, mes.getMessageId().toString()));
      WebUser user = webUserService.findUserInfoFromCache(authorId);
      if (user.getState() != 0 || user.getIsDel() == 1 || user.getSuperiorState() != 0) {
        result.getResult().removeAll(result.getResult());
        break;
      }
      //列表页评论数据=礼物数+评论数
      mes.setCommentCount(mes.getPresentCount() + mes.getCommentCount());
      mes.setUserType(String.valueOf(user.getUserType()));
      mes.setNickName(user.getNickName());
      mes.setHeadImg(user.getHeadImg());
      Map map = Maps.newHashMap();
      List list = new ArrayList();
      map.put("pictureUrls", mes.getPictureUrls());
      map.put("month", "");
      map.put("year", "");
      list.add(map);
      mes.setArticleContent(list);
    }
    return result;
  }

  /**
   * 取消置顶
   *
   * @param userId
   * @param messageId
   * @return
   * @throws Exception
   */
  @Override
  public int unTop(String userId, String messageId) throws Exception {
    //更新数据库
    int result=dynamicDao.unTop(userId, messageId);
    //清除缓存
    redisDynamicService.updateUserFeedsScore(userId, Integer.parseInt(messageId), Double.parseDouble(messageId) * -1);
    return result;

  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public ResultBean deleteMessage(Message mes) throws Exception {
    ResultBean resultBean = new ResultBean();
    logger.info("用户userId={}删除动态={}", mes.getUserId(), mes.getMessageId());
    //0.获取动态内容,判断动态是否属于该用户
    String userId = mes.getUserId();
    mes = redisDynamicService.getMessageInfo(String.valueOf(mes.getMessageId()));
    if (mes == null || !userId.equals(mes.getUserId())) {
      logger.error("动态信息id={}不存在或不属于userId={}", JSONObject.toJSONString(mes), userId);
      resultBean.setCode(ResultCode.SUCCESS.get_code());
      resultBean.setMsg("动态不存在或不属于你");
      return resultBean;
    }
    //1.先删除缓存
    try {
      redisDynamicService.delMessageCache(mes);
    } catch (Exception e) {
      logger.error("缓存删除动态异常", e);
      try {
        redisDynamicService.delMessageCache(mes);
      } catch (Exception e1) {
        logger.error("缓存删除动态异常", e);
      }
    }
    //2.删除DB操作
    dynamicDao.deleteMessage(mes.getUserId(), mes.getMessageId().toString());
    //1.1图文类，删除相册
    if (Integer.valueOf(mes.getMessageType()) == MessageConstant.PICTURE) {
      DynamicAlbum dynamicAlbum = new DynamicAlbum();
      dynamicAlbum.setMsgId(mes.getMessageId());
      dynamicAlbumDao.deleteAlbumByParams(dynamicAlbum);
    }
    resultBean.setCode(ResultCode.SUCCESS.get_code());
    resultBean.setMsg("删除动态成功");

    return resultBean;
  }

  @Override
  public void addMessageCount(String messageId, String userId, String type) throws Exception {
    //更新动态数、评论数和礼物数
    dynamicDao.addMessageCount(messageId, type);
    //刷新内容
    Message message = dynamicDao.getMessageById(messageId);
    redisDynamicService.syncMessage(message);
  }

  @Override
  public void reMessageCount(String messageId, String userId, String type) {

    dynamicDao.reMessageCount(messageId, type);
    //刷新内容
    Message message = dynamicDao.getMessageById(messageId);
    redisDynamicService.syncMessage(message);
  }

  /**
   * 主播分享动态
   *
   * @param liveDynamicVo
   * @return
   */
  @Override
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public int shareLive(LiveDynamicVo liveDynamicVo) {
    int isSquare = squareUserCheckService.checkSquareUserId(liveDynamicVo.getUserId()) ? 1 : 0;
    return dynamicDao.shareLive(liveDynamicVo, isSquare);
  }

  /**
   * 查看直播是否被分享过动态 false:未分享过
   *
   * @return
   */

  public boolean isShareToDynamic(String userId, String liveUuid) {
    return dynamicDao.isShareToDynamic(userId, liveUuid);
  }

  @Override
  public List listFans(String userId) {

    Map<String, String> config = clubConfigCenter.getPublicConfig();
    logger.info("userId={},url={}", userId, config.get("list.fans") + "_" + userId + ".json");
    String fans = HttpClientUtils.doGet(config.get("list.fans") + "_" + userId + ".json", null, "utf-8");
    List listFans = new ArrayList();
    if (StringUtils.isEmpty(fans)) {

      return listFans;
    }

    JSONObject jsonObject = JSON.parseObject(fans);
    List list = jsonObject.getJSONObject("data").getJSONArray("dataValue");
    int num = list.size() >= 3 ? 3 : list.size();
    if (list.isEmpty()) {
      return listFans;
    } else {
      for (int i = 0; i < num; i++) {
        JSONObject obj = (JSONObject) list.get(i);
        Map map = Maps.newHashMap();
        map.put("headImg", obj.get("headImg"));
        map.put("payCount", 0);
        listFans.add(map);
      }
      return listFans;
    }
  }

  /**
   * 修改内容:新增保存is_square字段
   * 修改时间:2017/03/10
   * 修改人:葛玉琦
   *
   * @param message
   * @return
   */
  @Override
  @SuppressWarnings("rawtypes")
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public ResultBean insertMessage(Message message) throws Exception {
    Profiler profiler=new Profiler("发表动态开始");
    ResultBean resultBean = new ResultBean();
    profiler.start("验证用户是否允许发送动态");
    Map<String,String>config=clubConfigCenter.getPublicConfig();
    //缓存动态内容
    boolean result = isSendMessage(message.getUserId());
    if (!result) {
      resultBean.setCode(ResultCode.MessageUpperLimit.get_code());
      resultBean.setMsg(config.get("surplusMsg"));
      return new ResultBean();
    }
    profiler.start("验证用户是否存在");
    // 用户是否存在
    WebUser user = webUserService.getWebUserInfoByUserId(message.getUserId());
    if (user == null) {
      return new ResultBean(ResultCode.LoginUserIsNotExist);
    }
    profiler.start("验证用户动态是否上广场");
    //检查动态是否可以进入广场
    boolean isSquare = squareUserCheckService.checkSquareUserId(message.getUserId());
    logger.info("用户userId={}发布动态，是否允许进入广场={}", message.getUserId(), isSquare);
    if (isSquare) {
      message.setIsSqure(1);
    }
    message.setJobId("");
    message.setMessageTime(new Date());
    //视频文字
    if (Integer.valueOf(message.getMessageType()) == MessageConstant.VIDEOS) {
      profiler.start("用户动态视频逻辑");
      message.setTranscode(false);
      if (StringUtils.isEmpty(message.getPath())) {
        return new ResultBean(ResultCode.ParamException.get_code(), "视频路径为空");
      }
      // 获取转码id 如果失败存入error
      String jobId = "error";
      for (int i = 0; i < 3; i++) {
        jobId = getJobId(message.getBucket(), message.getPath());
        if (jobId.equals("error")) {
          try {
            Thread.sleep(1000);
          } catch (Exception e) {
            e.printStackTrace();
          }
        } else {
          break;
        }
      }
      message.setJobId(jobId);
    } else if (Integer.valueOf(message.getMessageType()) == MessageConstant.WORDS) {
      profiler.start("用户动态文字逻辑");
      //文字
      message.setBackImg("");
      message.setIsSync(0);
      message.setFromType("0");
      message.setLength("");
      message.setPath("");
      message.setTranscode(true);
    } else {
      profiler.start("用户动态图片逻辑");
      //图文
      message.setTranscode(true);
    }
    profiler.start("用户动态保存逻辑");
    //保存动态
    int id = dynamicDao.saveObj(message);
    message.setMessageId(id);
    if (id > 0) {
      resultBean = new ResultBean(ResultCode.SUCCESS);
      if (Integer.valueOf(message.getMessageType()) == MessageConstant.PICTURE) {
        //动态保存成功，并且图文，处理相册
        profiler.start("用户动态保存相册逻辑");
        addAlbum(message);
      }
    }
    message.setTopStatus("0");
    message.setIsDel(0);
    //缓存动态和记录已发送条数
    profiler.start("用户动态缓存逻辑");
    redisDynamicService.syncMessage(message);
    Map<String, String> map = Maps.newHashMap();
    map.put("surplus", "-1");
    map.put("surplusMsg", config.get("surplusMsg"));
    // 主播、明星、片场 发送动态不受限制
    profiler.start("用户动态缓存每日条数逻辑");
    if (!UserTypeEnum.isAnchor(user.getUserType())) {
      redisDynamicService.incrMessageCount(message.getUserId());
      int total = redisDynamicService.getMessageTotalByUserId(message.getUserId());
      Integer limitCount = org.apache.commons.lang3.StringUtils.isBlank(config.get("limitCount")) ? 20 : Integer.parseInt(config.get("limitCount"));
      map.put("surplus", limitCount > total ?String.valueOf(limitCount - total ): "0");
    }
    resultBean.setData(map);
    profiler.stop().print();
    return resultBean;
  }

  @Override
  public void videoCallback(String jobId, String pathTrans) throws Exception {
    Message message = dynamicDao.getMessageInfoByJobId(jobId);
    if (message == null) {
      throw new Exception(String.format("水印转码成功后，jobId=%s回调动态不存在", jobId));
    }

    // 水印转码成功后，回调
    dynamicDao.updateTranscode(jobId, pathTrans);
    /*//转码中的key删除，录入到user_feed中
    redisDynamicService.removeTranscodingToFeeds(message);*/

  }

  /**
   * 获取jobId
   *
   * @return
   */
  private String getJobId(String bucket, String videoUrl) {
    logger.info("转码Object={}, bucketName={}", videoUrl, bucket);
    String res = videoTranscodeUtil.transcode(bucket, getvideoObject(videoUrl));
    if (StringUtils.isNotEmpty(res)) {
      JSONObject jsonObj = JSONObject.parseObject(res);
      logger.info("转码返回Json=" + jsonObj.toJSONString());
      if (jsonObj.getInteger("code") == 200) {
        return JSONObject.parseObject(jsonObj.getString("data")).getString("jobId");
      }
    } else {
      logger.error("转码失败");
    }
    return "error";
  }

  /**
   * 添加相册或时添加message_album
   *
   * @param message
   * @return
   */
  private int addAlbum(Message message) throws Exception {
    logger.info("保存相册params={}", JSONObject.toJSONString(message));
    int code = 0;
    DynamicAlbum dynamicAlbum = new DynamicAlbum();
    dynamicAlbum.setCreateUser("");
    dynamicAlbum.setIsDel(0);
    dynamicAlbum.setIsSync(message.getIsSync());
    dynamicAlbum.setMessageInfo(message.getMessageInfo());
    dynamicAlbum.setMsgId((int) message.getMessageId());
    dynamicAlbum.setUserId(String.valueOf(message.getUserId()));
    if (message.getMessageType().equals("2")) {
      List<String> paths = StringUtil.splitToList(",", message.getPath());
      for (String path : paths) {
        dynamicAlbum.setPath(path);
        code = dynamicAlbumDao.saveObj(dynamicAlbum);
      }
    }
    return code;
  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public int admire(String userId, String messageId) throws Exception {
    //查询动态
    Message message = redisDynamicService.getMessageInfo(messageId);
    if (message == null) {
      throw new DataIllegalException(String.format("动态ID=%s,内容不存在", messageId));
    }
    //点赞缓存
    redisDynamicService.setPraiseToRedis(userId, messageId);
    PraiseLog log = new PraiseLog();
    log.setMessageId(Integer.valueOf(messageId));
    log.setUserId(Integer.valueOf(userId));
    this.addMessageCount(messageId, userId, String.valueOf(MessageConstant.PRAISECOUNT));
    return dynamicDao.insertPraiseLog(log);
  }

  @Override
  public WebUser getDynaUser(String userId) {
    WebUser web = webUserService.getDynaUser(userId);
    if (null != web) {
      web.setWatcherCount(watchService.findWatchedCount(userId));
      web.setFansCount(watchService.findAllFansCount(userId));
      String authInfo = userAuthService.findAnchorInfo(web);
      web.setAuthInfo(authInfo);
    } else {
      logger.info("获取的用户信息为空");
    }
    return web;
  }

  @Override
  public List recommendMesStarClubFor(String userId) {
    List<RecommendForStar> user = new ArrayList<RecommendForStar>();
    //获取俱乐部人的基本信息
    WebUser userTemp=webUserService.getWebUserInfoByIsDel(userId,2);
    //用户是否存在
    logger.info("查看用户主播userId={},不存在",userId);
    if(userTemp == null){
      return user;
    }
    //判断是否为主播
    if(!UserTypeEnum.isAnchor(userTemp.getUserType())){
      return user;
    }

    Map map = watchService.getrelationIds(userId);
    if (StringUtils.isEmpty(map.get("ids").toString())) {

      return user;
    }

    String ids[] = map.get("ids").toString().split(",");
    if (ids.length == 0) {

      return user;

    }
    StringBuilder inUserId = new StringBuilder();
    for (String id : ids) {
      inUserId = inUserId.append("'").append(id).append("'").append(",");
    }

    inUserId.deleteCharAt(inUserId.length() - 1);
    user = watchService.recommendMesStarClubFor(inUserId.toString());
    for (RecommendForStar webUser : user) {
      //新关注关系 0关注1互粉2未关注
      //webUser.setRelation(watchCacheService.getWatchRelationByUserId(userId, webUser.getId()));
      webUser.setIsFollow(watchCacheService.getWatchRelationByUserId(userId, webUser.getId()));
      webUser.setWatchedCount((int) watchService.findWatchedCount(userId));
      webUser.setFansCount((int) watchService.findAllFansCount(userId));
    }
    return user;
  }

  /**
   * 获取视频object
   *
   * @param path
   * @return
   */
  private String getvideoObject(String path) {
    int postion = path.indexOf(".com/") + 5;
    return path.substring(postion);
  }

  /**
   * 检查用户是否赞过动态
   * @param userId
   * @param messageId
   * @return 1 已点赞 0 未点赞
   */
  private int checkPraise(String userId, String messageId) {
    logger.info("检查用户userId={}是否赞过动态id={}", userId, messageId);
    try {
      String key = String.format(RedisKeyConstant.PRAISE_SORTED_KEY, messageId);
      Double score = jedisService.zscore(key, userId);
      logger.info("动态：{}的点赞列表，key：{}，userId：{}的score：{}", messageId, key, userId, score);

      if (score == null || score <= 0) {
        return 0;
      }else {
        return 1;
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("获取userId:{}对messageId:{}的点赞状态失败", userId, messageId);
      return 0;
    }
  }

  @Override
  public Map<Integer, MessageResVo> getMessageResByIds(List<Integer> ids) {
    List<Map<String, Object>> list = dynamicDao.getMessageResByIds(ids);
    Map<Integer, MessageResVo> resMap = Maps.newHashMap();
    if (!CollectionUtils.isEmpty(list)) {
      for (Map<String, Object> map : list) {
        if (CollectionUtils.isEmpty(map)) {
          continue;
        }
        MessageResVo mes = new MessageResVo();
        mes.messageId = map.get("id") == null ? 0 : Integer.parseInt(map.get("id").toString());
        mes.mesUserId = map.get("user_id") == null ? "" : map.get("user_id").toString();
        WebUser user = webUserService.getWebUserInfoByUserId(mes.mesUserId);
        if (user == null) {
          return null;
        }
        mes.mesHeadImg = user.getHeadImg();
        mes.mesNickName = user.getNickName();
        mes.mesUserType = user.getUserType();
        mes.mesSex = user.getSex();
        mes.mesLevel = String.valueOf(user.getUserLevel());
        mes.messageInfo = map.get("message_info") == null ? "" : map.get("message_info").toString();
        mes.mesStatus = 0;
        if (map.get("is_del") != null) {
          if (!map.get("is_del").toString().equals("1")) {
            mes.mesStatus = 1;
          }
        }
        mes.messageTime = map.get("message_time") == null ? "" : map.get("message_time").toString();
        resMap.put(mes.messageId, mes);
      }
    }
    return resMap;
  }

  @Override
  public Map getMessageInfoById(long messageId) {
    return this.dynamicDao.getMessageInfoById(messageId);
  }

  /**
   * 获取关注小红点
   */
  @Override
  public boolean followRedDot(String userId, int messageId) {
    StringBuilder userIds = new StringBuilder();
    try {
      //            List user = watchService.listWatchInfo(userId);
      List user = watchCacheService.getAllWatchUserIdList(userId);
      for (int i = 0; i < user.size(); i++) {
        userIds.append("'");
        userIds.append(user.get(i));
        userIds.append("'");
        userIds.append(",");
      }
      if (user.size() > 0) {
        userIds.deleteCharAt(userIds.length() - 1);
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("获取用户关注的主播的最新动态ID出错");
      return false;
    }
    String newId = dynamicDao.getWatcherNewMessageId(userIds.toString());
    int newIdInt = 0;
    if (StringUtils.isNotEmpty(newId)) {
      logger.info("关注的人的最新动态ID：{}", newId);
      newIdInt = Integer.valueOf(newId);
    } else {
      logger.error("关注的人的最新动态ID获取失败");
    }
    if (newIdInt > messageId) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 查询普通用户今日已发送条数
   *
   * @param userId
   * @return int
   * @description （用一句话描述该方法的适用条件执行流程、适用方法、注意事项- 可选）
   * @author wangchao
   * @create 2017-03-23 13:53
   */
  @Override
  public boolean isSendMessage(String userId) throws Exception {
    WebUser user = webUserService.getWebUserInfoByUserId(userId);
    if (!UserTypeEnum.isAnchor(user.getUserType())) {
      long total = redisDynamicService.getMessageTotalByUserId(user.getUserId());
      Map<String,String>config=clubConfigCenter.getPublicConfig();
      int limitCount = org.apache.commons.lang3.StringUtils.isBlank(config.get("limitCount")) ? 20 : Integer.parseInt(config.get("limitCount"));
      if (total > limitCount) {
        return false;
      }
    }
    return true;
  }
}
